import { defineStore } from "pinia";
import { login, logout, getInfo } from "@/api/login";
import { getImgUrl, getAuthentication } from "@/api/decor/designer";
import { getAuthenticationAgency } from "@/api/decor/designAgency";
import { getMaterialAuthentication } from "@/api/decor/materialSupplier";
import { getToken, setToken, removeToken } from "@/utils/auth";
import defAva from "@/assets/images/profile.jpg";

const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    name: "",
    nickname: "",
    userId: "",
    avatar: "",
    roles: [],
    rolesList: [],
    permissions: [],
  }),
  actions: {
    // 登录
    login(userInfo) {
      const tenantId = userInfo.tenantId;
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(tenantId, username, password, code, uuid)
          .then((res) => {
            setToken(res.data.access_token);
            this.token = res.data.access_token;
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const data = res.data;
            const user = data.user;
            let profile = "";
            if (data.roles && data.roles.length > 0) {
              this.rolesList = data.roles;
              this.permissions = data.permissions;
              // 验证返回的roles是否是一个非空数组
              if (
                sessionStorage.getItem("currentRoles") === null ||
                sessionStorage.getItem("currentRoles") === undefined
              ) {
                // 检查是否包含 'Designer'
                const index = data.roles.indexOf("Designer");
                if (index !== -1) {
                  this.roles = "Designer";
                } else {
                  this.roles = data.roles[0];
                }
              } else {
                this.roles = sessionStorage.getItem("currentRoles");
              }
            } else {
              this.roles = ["ROLE_DEFAULT"];
            }
            // avatar
            if (this.roles === "DesignOrganization") {
              // 机构
              getAuthenticationAgency().then((res) => {
                let imgUrlPromises = [];
                if (res.avatar) {
                  let avatarPromise = getImgUrl(res.avatar).then((res) => {
                    profile = res.data[0].url;
                  });
                  imgUrlPromises.push(avatarPromise);
                  Promise.all(imgUrlPromises).then(() => {
                    this.avatar = profile;
                  });
                }
              });
            } else if (this.roles === "Designer") {
              // 设计师
              getAuthentication().then((res) => {
                let imgUrlPromises = [];
                if (res.avatarId) {
                  let avatarPromise = getImgUrl(res.avatarId).then((res) => {
                    profile = res.data[0].url;
                  });
                  imgUrlPromises.push(avatarPromise);
                }
                Promise.all(imgUrlPromises).then(() => {
                  this.avatar = profile;
                });
              });
            } else if (this.roles === "Material") {
              // 材料商
              getMaterialAuthentication().then((res) => {
                let imgUrlPromises = [];
                if (res.avatar) {
                  let avatarPromise = getImgUrl(res.avatar).then((res) => {
                    profile = res.data[0].url;
                  });
                  imgUrlPromises.push(avatarPromise);
                }
                Promise.all(imgUrlPromises).then(() => {
                  this.avatar = profile;
                });
              });
            } else if (this.roles === "Common") {
              let imgUrlPromises = [];
              let avatarPromise = getImgUrl(user.avatar).then((response) => {
                profile = response.data[0].url;
              });
              imgUrlPromises.push(avatarPromise);
              Promise.all(imgUrlPromises).then(() => {
                this.avatar = profile;
              });
            } else if (this.roles === "Admin") {
              profile = defAva;
              this.avatar = profile;
            } else {
              // 管理员
              profile = user.url == null || user.url == "" ? defAva : user.url;
              this.avatar = profile;
            }
            this.userId = user.userId;
            this.name = user.userName;
            this.nickname = user.nickName;
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        logout(this.token)
          .then(() => {
            this.token = "";
            this.roles = [];
            this.permissions = [];
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
});

export default useUserStore;
